#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python常用模块库 
@File ：daemon.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/21 上午8:58 
"""

from pathlib import Path

import daemon
from daemon import pidfile


class LinuxDaemon:
	def __init__(self, config_path: Path):
		self.config_path = config_path
		self.pid_file = "/var/run/file_monitor.pid"

	def start(self):
		"""启动守护进程"""
		context = daemon.DaemonContext(
			pidfile=pidfile.TimeoutPIDLockFile(self.pid_file),
			files_preserve=[hdl.stream for hdl in logging.getLogger().handlers],
			detach_process=True,
			prevent_core=True
		)
		with context:
			from ..core.monitor import FileMonitor
			monitor = FileMonitor.load_config(self.config_path)
			monitor.run()

	def stop(self):
		"""停止守护进程"""
		if Path(self.pid_file).exists():
			with open(self.pid_file) as f:
				pid = int(f.read().strip())
				os.kill(pid, signal.SIGTERM)
